package io.renren.modules.admin.controller;

import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.utils.*;
import io.renren.modules.admin.entity.vo.DevHttpJsonVo;
import io.renren.modules.admin.entity.vo.PhoneEntityVo;
import io.renren.modules.admin.service.AccountUpService;
import io.renren.modules.admin.service.ManagerWorkService;
import io.renren.modules.admin.service.WarmUpService;
import io.renren.modules.app.annotation.Login;
import io.renren.modules.app.annotation.LoginUser;
import io.renren.modules.app.interceptor.AuthorizationInterceptor;
import org.apache.commons.lang.StringUtils;
import org.quartz.management.ManagementServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import io.renren.modules.admin.entity.PhoneEntity;
import io.renren.modules.admin.service.PhoneService;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;

/**
 * @author fangzq
 * @email canglx1996@163.com
 * @date 2020-12-01 16:06:19
 */
@RestController
@RequestMapping("admin/phone")
public class PhoneController {
    @Autowired
    private PhoneService phoneService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private WarmUpService warmUpService;
    @Autowired
    private ManagerWorkService managerWorkService;
    @Autowired
    private AccountUpService accountUpService;
    @Autowired
    private AuthorizationInterceptor authorizationInterceptor;

    /**
     * 获取状态空闲的手机编号集合
     */
    public List<String> getFreePhoneNumList(int num,Long userId){
        ResponseEntity<String> results = this.restTemplate.exchange("http://dou.shciyun.com/open/common/device/list?userId="+userId, HttpMethod.GET, null, String.class);
        String json = results.getBody();
        DevHttpJsonVo devHttpJsonVo=  JSON.parseObject(json.toString(),DevHttpJsonVo.class);
        JSONObject data1 = devHttpJsonVo.getData();
        JSONArray devices = data1.getJSONArray("devices");
        String js = JSONObject.toJSONString(devices);

        List<PhoneEntityVo> phoneEntityVos = new ArrayList<>();
        devices.forEach(item->{
            PhoneEntityVo phoneEntityVo = JSONObject.toJavaObject((JSONObject) item, PhoneEntityVo.class);
            phoneEntityVos.add(phoneEntityVo);
        });
        if (phoneEntityVos == null) {
            return null;
        }
        List<String> free = new ArrayList<>();
        for (int i = 0; i < phoneEntityVos.size(); i++) {
            if (phoneEntityVos.get(i).getStatus() == 1 && phoneEntityVos.get(i).getTask() == null) {
                free.add(phoneEntityVos.get(i).getDeviceId());
                if (free.size() >= num) {
                    break;
                }
            }
        }
        return free;
    }

    /**
     * 远程接口手机列表
     * @return
     */
    @GetMapping("/api/list")
    public R list(HttpServletRequest request,@RequestParam Map<String, Object> params){
        Long userId = ShiroUtils.getUserId();
        if (userId == null) {
            return R.error("登录出错，请重新登录");
        }
//        Long userId = (Long) request.getAttribute(AuthorizationInterceptor.USER_KEY);
        ResponseEntity<String> results = this.restTemplate.exchange("http://dou.shciyun.com/open/common/device/list?userId=" + userId, HttpMethod.GET, null, String.class);
        String json = results.getBody();
        DevHttpJsonVo devHttpJsonVo=  JSON.parseObject(json,DevHttpJsonVo.class);
        JSONObject data1 = devHttpJsonVo.getData();
        JSONArray devices = data1.getJSONArray("devices");

        List<PhoneEntityVo> phoneEntityVos = new ArrayList<>();
        devices.forEach(item->{
            PhoneEntityVo phoneEntityVo = JSONObject.toJavaObject((JSONObject) item, PhoneEntityVo.class);
            phoneEntityVos.add(phoneEntityVo);
        });

        // 日期格式转化
        phoneEntityVos.forEach(phoneEntityVo -> {
            Date date = new Date(phoneEntityVo.getLoginTime());
            phoneEntityVo.setLoginDate(date);
            // TODO 格式化数据之后，依次保存到数据库，方便后期查询   暂时不用保存，每次查询去请求接口就可以了
            String deviceId = phoneEntityVo.getDeviceId();
            String taskName = this.warmUpService.queryNameByDeviceId(deviceId);
            if (taskName == null) {
                taskName = this.accountUpService.queryNameByDeviceId(deviceId);
            }else if (taskName == null) {
                taskName = this.managerWorkService.queryNameByDeviceId(deviceId);
            }else if (taskName == null) {
                taskName = "";
            }
            phoneEntityVo.setTaskName(taskName);
        });

        if (phoneEntityVos == null) {
            return R.error("未找到设备，请核实接口数据");
        }
        int freeCount = 0;
        int onlineCount = 0;
        int[] freePhone = getFreePhone();
        if (freePhone.length <= 1) {
            freeCount = 0;
            onlineCount = 0;
        }else {
            freeCount = freePhone[0];
            onlineCount = freePhone[1];
        }
        long page1 = Long.parseLong((String) params.get(Constant.PAGE));
        long limit = Long.parseLong((String) params.get(Constant.LIMIT));

        PageUtils page = new PageUtils(phoneEntityVos.subList((int)((page1-1)*limit),(int)(page1*limit)), phoneEntityVos.size(),(int)limit,(int)page1);
        return R.ok().put("page", page).put("countAll",phoneEntityVos.size()).put("freeCount",freeCount).put("onlineCount",onlineCount);
    }

    /**
     * 获取状态空闲的手机数
     */
    public int[] getFreePhone(){
        Long userId = ShiroUtils.getUserId();
        ResponseEntity<String> results = this.restTemplate.exchange("http://dou.shciyun.com/open/common/device/list?userId="+userId, HttpMethod.GET, null, String.class);
        String json = results.getBody();
        DevHttpJsonVo devHttpJsonVo=  JSON.parseObject(json.toString(),DevHttpJsonVo.class);
        JSONObject data1 = devHttpJsonVo.getData();
        JSONArray devices = data1.getJSONArray("devices");

        List<PhoneEntityVo> phoneEntityVos = new ArrayList<>();
        devices.forEach(item->{
            PhoneEntityVo phoneEntityVo = JSONObject.toJavaObject((JSONObject) item, PhoneEntityVo.class);
            phoneEntityVos.add(phoneEntityVo);
        });
        if (phoneEntityVos == null) {
            return new int[]{};
        }
        int free = 0;
        int online = 0;
        for (int i = 0; i < phoneEntityVos.size(); i++) {
            if (phoneEntityVos.get(i).getStatus() == 1 && phoneEntityVos.get(i).getTask() == null) {
                free++;
            }
        }
        for (int i = 0; i < phoneEntityVos.size(); i++) {
            if (phoneEntityVos.get(i).getStatus() == 1) {
                online++;
            }
        }
        return new int[]{free,online};
    }

    /**
     * 通过手机编号找到手机别名
     */
//    @RequestMapping("getAliasById")
    public String getAliasById(String phoneId,Long userId) {
        ResponseEntity<String> results = this.restTemplate.exchange("http://dou.shciyun.com/open/common/device/list?userId="+userId, HttpMethod.GET, null, String.class);
        String json = results.getBody();
        DevHttpJsonVo devHttpJsonVo=  JSON.parseObject(json.toString(),DevHttpJsonVo.class);
        JSONObject data1 = devHttpJsonVo.getData();
        JSONArray devices = data1.getJSONArray("devices");
        String js = JSONObject.toJSONString(devices);

        List<PhoneEntityVo> phoneEntityVos = new ArrayList<>();
        devices.forEach(item->{
            PhoneEntityVo phoneEntityVo = JSONObject.toJavaObject((JSONObject) item, PhoneEntityVo.class);
            phoneEntityVos.add(phoneEntityVo);
        });
        String alias = "";
        for (PhoneEntityVo phoneEntityVo : phoneEntityVos) {
        String deviceId = phoneEntityVo.getDeviceId();
            if (StringUtils.equals(deviceId,phoneId)) {
                alias = phoneEntityVo.getAlias();
            }
        }
        return alias;
    }



    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = phoneService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        PhoneEntity phone = phoneService.getById(id);

        return R.ok().put("phone", phone);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody PhoneEntity phone) {
        phoneService.save(phone);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody PhoneEntity phone) {
        phoneService.updateById(phone);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
        phoneService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
